package cj.web.weixin.controllers;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.weixin.CheckUtil;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.login.controllers.BaseController;
import cj.web.marriage.dao.UserApplicationDAO;
import cj.web.marriage.domain.UserApplication;

/**
 * 婚典平台微信公众号开发
 * @author Administrator
 *
 */
@Path("")
public class DemoWeiXinController extends BaseController{
	
	private static Logger logger = Logger.getLogger(DemoWeiXinController.class.getName());
	
	@Autowired
	private UserApplicationDAO userApplicationDAO;
	
	@Get("getweixincode")
	public String getWeiXinCode(@Param("code") String code) throws UnsupportedEncodingException
	{
		JSONObject jopublic =new JSONObject();
		//操作成功
		jopublic.put("returnFlag", Constants.returnObj.returnFlag_true);
		try {
			//Step1
//			model.add("code",code);
			//Step2
			String openid = HttpsWenXinUtil.retOpenId(code, Constants.weixinkey.AppID, Constants.weixinkey.AppSecret);
			
			return "r:/demo/imageDemo";
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("=============getWeiXinCode is "+e.getLocalizedMessage(),e);
			//1:flase
			jopublic.put("returnFlag", Constants.returnObj.returnFlag_flase);
			jopublic.put("returnMsg", "operation is error");
			
			return "r:/demo/imageDemo";
		}
	}
	
	/**
	 * 微信验证消息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@Get("weixinmarry")
	public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
		/*
		 * signature 微信加密签名， signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		 * timestamp 时间戳 nonce 随机数 echostr 随机字符串
		 */
		String echostr = request.getParameter("echostr");
		if (echostr != null && CheckUtil.checkSignature(request)) {
			// 响应消息
			HttpsWenXinUtil.print(response,echostr);
		}
	}
	
	/**
	 * 微信发送消息Process
	 * @param request
	 * @param response
	 * @return
	 */
	@Post("weixinmarry")
	public String processRequest(HttpServletRequest request, HttpServletResponse response) {
		String respMessage = null;
		try {
			
			// xml请求解析
			Map<String, String> requestMap = HttpsWenXinUtil.parseXml(request);
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
//			System.out.println("-----------"+requestMap.toString());
			//返回内容
			String respContent = "";
			//幸福码
			String code = "";

			//获取微信用户信息------------
			UserApplication obj = userApplicationDAO.queryByOpenId(fromUserName);
			
			//不存在
			if(obj==null)
			{
				code = saveUserFengSi(fromUserName);
			}
			else
			{
				code = String.valueOf(obj.getId());
			}

			//------------微信事件判断
			if (msgType.equals(Constants.weixinkey.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");

				if (eventType.equals(Constants.weixinkey.EVENT_TYPE_SUBSCRIBE)) {
					// 关注
					respContent = "感谢您关注偶,这里会给您提供最新的资讯和公告！\n";
					StringBuffer contentMsg = new StringBuffer();
					contentMsg.append("您的幸福码是："+code).append("\n");
					respContent = respContent+contentMsg.toString();
					
				} else if (eventType.equals(Constants.weixinkey.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消关注,用户接受不到我们发送的消息了，可以在这里记录用户取消关注的日志信息

				} 
				else if (eventType.equals(Constants.weixinkey.EVENT_TYPE_CLICK)) {
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");
					// 自定义菜单点击事件
					if ("wyyy".toUpperCase().equals(eventKey.toUpperCase())) {
//						System.out.println("-----"+eventKey);
						respMessage="<xml>"
								+ "<ToUserName><![CDATA["+toUserName+"]]></ToUserName>"
								+ "<FromUserName><![CDATA["+fromUserName+"]]></FromUserName>"
								+ "<CreateTime><![CDATA["+new Date().getTime()+"]]></CreateTime>"
								+ "<MsgType><![CDATA["+Constants.weixinkey.REQ_MESSAGE_TYPE_EVENT+"]]></MsgType>"
								+ "<Event><![CDATA["+Constants.weixinkey.RESP_MESSAGE_TYPE_VIEW+"]]></Event>"
								+ "<EventKey><![CDATA[http://www.qq.com]]></EventKey>"
								+ "</xml>";
					} 
				}
				
				respMessage = HttpsWenXinUtil.respMessage(fromUserName,toUserName,respContent,Constants.weixinkey.RESP_MESSAGE_TYPE_TEXT);
				
			} else if (msgType.equals(Constants.weixinkey.RESP_MESSAGE_TYPE_TEXT)) {
				String Content = requestMap.get("Content");
				// 自定义菜单点击事件
				if ("marry".toUpperCase().equals(Content.toUpperCase())) {
					respContent = "您的幸福码是："+code;
				} 
				
				respMessage = HttpsWenXinUtil.respMessage(fromUserName,toUserName,respContent,Constants.weixinkey.RESP_MESSAGE_TYPE_TEXT);
			}
			
//			TextMessage textMessage = new TextMessage();
//			textMessage.setToUserName(fromUserName);
//			textMessage.setFromUserName(toUserName);
//			textMessage.setCreateTime(new Date().getTime());
//			textMessage.setMsgType(RESP_MESSAGE_TYPE_TEXT);
//			textMessage.setContent(respContent);
//			respMessage = MessageUtil.textMessageToXml(textMessage);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		HttpsWenXinUtil.print(response,respMessage);
		return "";
	}
	
	/**
	 * 保存用户粉丝信息
	 * @param openid
	 * @return 返回用户粉丝幸福码
	 */
	private String saveUserFengSi(String openid)
	{
		//获取微信access_token
		String access_token = HttpsWenXinUtil.initWeiXin(Constants.weixinkey.AppID,Constants.weixinkey.AppSecret);
		
		//获取用户信息
		//转换Json
		JSONObject jsUserObj =HttpsWenXinUtil.retWeixinUserInfo(access_token, openid);
		//对象
		UserApplication objs = new UserApplication();
		objs.setCity(jsUserObj.get("city").toString());
		objs.setCountry(jsUserObj.get("country").toString());
		objs.setHeadimgurl(jsUserObj.get("headimgurl").toString());
		objs.setNickname(jsUserObj.get("nickname").toString());
		objs.setOpenid(jsUserObj.get("openid").toString());
		objs.setProvince(jsUserObj.get("province").toString());
		objs.setSex(jsUserObj.get("sex").toString());
		//幸福码Code
		int id = userApplicationDAO.create(objs);
		
		return String.valueOf(id);
	}
}
